import res from "src/utils/response";
import {
  add as project_add,
  remove as project_remove,
  modify as project_modify,
  query as project_query,
} from "src/validators/project";
import {
  remove as snapshot_remove,
  query as snapshot_query,
} from "src/validators/snapshot";
import {
  clone as operate_clone,
  pull as operate_pull,
  install as operate_install,
  build as operate_build,
  deploy as operate_deploy,
  rewind as operate_rewind,
  gitlog as operate_gitlog,
} from "src/validators/operate";

const schema = {
  // 项目
  project_add,
  project_remove,
  project_modify,
  project_query,
  // 快照
  snapshot_remove,
  snapshot_query,
  // 操作
  operate_clone,
  operate_pull,
  operate_install,
  operate_build,
  operate_deploy,
  operate_rewind,
  operate_gitlog,
};

export default async (ctx: Context, next: Next, name: API.SchemaKey) => {
  if (schema[name]) {
    const { query, body } = ctx.request;
    const params = Object.keys(query).length === 0 ? body : query;
    const { error, value } = schema[name].validate(params || {});
    if (error) {
      ctx.body = res.fail(error);
      return;
    }
    ctx.state.params = value;
    await next();
  } else {
    ctx.body = res.fail("不存在该接口");
  }
};
